<template>
  <ElDialog
    v-bind="getBindValue"
    :fullscreen="isFullscreen"
    destroy-on-close
    lock-scroll
    draggable
    top="0"
    :close-on-click-modal="false"
    :show-close="false"
  >
    <template #header="{ close }">
      <div class="header">
        <slot name="title">
          {{ title }}
        </slot>
        <div class="icon-close">
          <i-ep-close @click="close" />
        </div>
      </div>
    </template>

    <ElScrollbar :style="dialogStyle">
      <slot></slot>
    </ElScrollbar>

    <template v-if="slots.footer" #footer>
      <slot name="footer"></slot>
    </template>
  </ElDialog>
</template>

<script setup>
import { computed, useAttrs, ref, unref, useSlots, watch, nextTick } from 'vue'
import { typeOf } from '@/utils/common'

const slots = useSlots()
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '标题'
  },
  fullscreen: {
    type: Boolean,
    default: false
  },
  maxHeight: {
    type: String || Number,
    default: '400px'
  }
})

const getBindValue = computed(() => {
  const delArr = ['fullscreen', 'title', 'maxHeight']
  const attrs = useAttrs()
  const obj = { ...attrs, ...props }
  for (const key in obj) {
    if (delArr.indexOf(key) !== -1) {
      delete obj[key]
    }
  }
  return obj
})

const isFullscreen = ref(false)

// console.log(typeOf(props.maxHeight))
const dialogHeight = ref(
  typeOf(props.maxHeight) === 'number' ? `${props.maxHeight}px` : props.maxHeight
)

watch(
  () => isFullscreen.value,
  async (val) => {
    await nextTick()
    if (val) {
      const windowHeight = document.documentElement.offsetHeight
      dialogHeight.value = `${windowHeight - 55 - 60 - (slots.footer ? 63 : 0)}px`
    } else {
      dialogHeight.value =
        typeOf(props.maxHeight) === 'number' ? `${props.maxHeight}px` : props.maxHeight
    }
  },
  {
    immediate: true
  }
)

const dialogStyle = computed(() => {
  return {
    height: unref(dialogHeight)
  }
})
</script>
<style lang="scss" scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 2rem;
}
.icon-close {
  cursor: pointer;
}
</style>
